import express from 'express';
import config from 'config'; // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
import cookieParser from 'cookie-parser';
import morgan from 'morgan';
import cors from 'cors';
import authorization from './middlewares/auth';
import errorHandle from './middlewares/error-handle';
import router from './router';
import runTask from './task';
import './mongodb';

import './models';
import './utils/publisher';

// 全局异常处理
process.on('unhandledRejection', (reason, p) => {
  console.log('Unhandled Rejection at: Promise ', p, ' reason: ', reason);
  // application specific logging, throwing an error, or other logic here
});

process.on('uncaughtException', (err) => {
  console.log('Caught exception: ', err);
});

const app = express();
app.use(morgan('combined'));
app.use(cors());

app.use((req, res, next) => {
  console.log(req.url)
  next();
});

// parse application/x-www-form-urlencoded
app.use(express.urlencoded({ limit: '10mb', extended: false }));

// parse application/json
app.use(express.json({ limit: '10mb' }));

// app.use(Statistic.apiRecord)
app.use(cookieParser());

app.use(authorization);

// 扩展 res.send() 方法
app.response.sendOk = function sendOk(data) {
  // code is intentionally kept simple for demonstration purpose
  return this.send({
    errCode: 0,
    errMsg: 'request:ok',
    data
  });
};

// Middleware to extract client IPv4 address
app.use((req, res, next) => {
  const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  // Extract IPv4 address from IP (IPv6 addresses can have '::' notation)
  const ipv4 = ip.includes(':') ? ip.split(':').pop() : ip;
  req.clientIPv4 = ipv4;
  next();
});

app.use(router);
// eslint-disable-next-line consistent-return
app.use(errorHandle);

// app.use(history());
// app.use(express.static('./public'));

const port = config.get('port') || process.env.port;
console.log('------------------', port);
app.listen(port, () => {
  console.log(
    `Server is running at http://localhost:${port}`
    // chalk.green(`Server is running at http://localhost:${config.port}`)
  );

  runTask();
});
